package site.immonkey.mailtest.template;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;

public class TemplateUtil {
	public static String compileTemplateText(String templatePath, Map<String, String> info) {
		InputStream in = TemplateUtil.class.getResourceAsStream("/template.html");
		String text;
		try {
			text = IOUtils.toString(in, "UTF-8");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		StringBuffer sb = new StringBuffer();
		Pattern pattern = Pattern.compile("\\{\\{\\s*(\\w+)\\s*\\}\\}");
		Matcher matcher = pattern.matcher(text);
		int prevIndex = 0;
		while(matcher.find()) {
			int start = matcher.start();
			sb.append(text.substring(prevIndex, start));
			prevIndex = matcher.end();
			
			String key = matcher.group(1);
			sb.append(info.get(key));
		}
		sb.append(text.substring(prevIndex));
		return sb.toString();
	}
}
